package licode.unisop.log.service.application.executor;

import licode.unisop.log.client.api.AuditLogApi;
import licode.unisop.log.client.api.AuditLogRecord;
import licode.unisop.log.client.api.CallingLogApi;
import licode.unisop.log.client.api.LoginLogApi;
import licode.unisop.log.client.dto.AuditLogDTO;
import licode.unisop.log.client.dto.CallingLogDTO;
import licode.unisop.log.client.dto.LoginLogDTO;
import licode.unisop.log.client.req.AuditLogIn;
import licode.unisop.log.client.req.CallingLogIn;
import licode.unisop.log.client.req.LoginLogIn;
import licode.unisop.types.event.DomainEvent;
import licode.unisop.types.event.DomainEventHandler;
import licode.unisop.types.event.DomainEventSubscribe;
import licode.unisop.types.event.LogDomainEvent;
import licode.unisop.unilite.dp.PageData;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 执行日志相关业务流程逻辑
 *
 * @author WR
 * @since 2016/7/12 13:02
 */
@Component
public class LogLogsExecutor implements DomainEventHandler {
    @Resource
    private AuditLogApi auditLogApi;

    @Resource
    private CallingLogApi callingLogApi;

    @Resource
    private LoginLogApi loginLogApi;

    @Resource
    private AuditLogRecord auditLogRecord;

    @Resource
    private DomainEventSubscribe domainEventSubscribe;

    @PostConstruct
    public void postConstruct() {
        domainEventSubscribe.subscribe(LogDomainEvent.class, this);
    }

    public void saveAudit(AuditLogDTO data) {
        auditLogApi.save(data);
    }

    public void saveCallingLog(CallingLogDTO data) {
        callingLogApi.save(data);
    }

    public void saveLogin(LoginLogDTO data) {
        loginLogApi.save(data);
    }

    public PageData<AuditLogDTO> auditList(AuditLogIn req) {
        return auditLogApi.query(req);
    }

    public PageData<CallingLogDTO> callApiList(CallingLogIn req) {
        return callingLogApi.query(req);
    }

    public PageData<LoginLogDTO> loginList(LoginLogIn req) {
        return loginLogApi.query(req);
    }

    @Override
    public <T extends DomainEvent> void handle(T event) {
        if (event instanceof LogDomainEvent) {
            LogDomainEvent lde = (LogDomainEvent)event;
            auditLogRecord.log(lde.getTokenInfo(), lde.getEventType(),
                    lde.getData(), lde.getErrorInfo());
        }
    }
}
